package com.collage.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.collage.entity.Activities;
import com.collage.entity.Bill;
import com.collage.entity.TeamPerson;
import com.collage.params.PageParams;
import com.collage.service.ActivitiesService;
import com.collage.service.BillService;
import com.collage.service.TeamPersonService;
import com.collage.util.Result;
import com.collage.vo.ActivitiesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/activities")
@AllArgsConstructor
public class ActivitiesController{
    public final ActivitiesService service;
    public final TeamPersonService tpService;
    public final BillService billService;

    public static String ACTIVITIES_STATUS_CLOSE = "已结束";

    @PostMapping("save")
    public Result saveActivities(@RequestBody Activities activities) {
        return  service.save(activities) ? Result.success() : Result.failed("新增失败");
    }

    @GetMapping("/list/{uid}")
    public Result getActivitiesList(@PathVariable String uid, PageParams params) {
        QueryWrapper<TeamPerson> teamPersonQueryWrapper = new QueryWrapper<>();
        teamPersonQueryWrapper.lambda().eq(TeamPerson::getUid, uid).eq(TeamPerson::getStatus, "通过");
        List<TeamPerson> list = tpService.list(teamPersonQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Result.success();
        }
        QueryWrapper<Activities> qw = new QueryWrapper<>();
        qw.lambda().in(Activities::getTid, list.stream().map(TeamPerson::getTid).collect(Collectors.toList()));
//                .ne(Activities::getStatus, ACTIVITIES_STATUS_CLOSE);
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        PageInfo<Activities> pageInfo = new PageInfo<>(service.list(qw));
        List<Activities> activities = pageInfo.getList();
        if (CollectionUtils.isEmpty(activities)) {
            return Result.success(activities, pageInfo.getTotal());
        }
        List<ActivitiesVO> voList = new ArrayList<>();
        activities.forEach(val -> {
            ActivitiesVO vo = new ActivitiesVO();
            BeanUtils.copyProperties(val, vo);
            QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
            billQueryWrapper.lambda().eq(Bill::getAid, val.getId());
            List<Bill> bills = billService.list(billQueryWrapper);
            if (bills.stream().map(Bill::getUid).collect(Collectors.toList()).contains(uid)) {
                vo.setAddStatus("已参与");
            } else {
                vo.setAddStatus("未参与");
            }
            voList.add(vo);
        });
        return Result.success(voList, pageInfo.getTotal());
    }

    @GetMapping("/close/{id}")
    public Result closeActivities(@PathVariable String id) {
        Activities activities = service.getById(id);

        QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
        billQueryWrapper.lambda().eq(Bill::getAid, id);
        List<Bill> bills = billService.list(billQueryWrapper);

        if (CollectionUtils.isEmpty(bills) || bills.stream().collect(Collectors.groupingBy(Bill::getUid)).size() < activities.getPerNum()) {
            return Result.failed("当前参加活动人数低于最低人数");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer sbf = new StringBuffer();
        sbf.append("活动：");
        sbf.append(activities.getName());
        sbf.append("，活动时间：");
        sbf.append(sdf.format(activities.getStartTime()));
        sbf.append("~");
        sbf.append(sdf.format(activities.getEndTime()));
        sbf.append("，参加活动人数：");
        sbf.append(bills.stream().collect(Collectors.groupingBy(Bill::getUid)).size());
        sbf.append(", 团购物品：");
        sbf.append(bills.stream().map(Bill::getName).distinct().collect(Collectors.joining(",")));
        sbf.append("，总价花费：");
        sbf.append(bills.stream().map(Bill::getPrice).reduce(BigDecimal::add).get());
        activities.setContext(sbf.toString());
        activities.setStatus(ACTIVITIES_STATUS_CLOSE);
        return service.updateById(activities) ? Result.success() : Result.failed("活动未结束");
    }
}